package com.sdgakj.service.manager;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.google.common.collect.Maps;
import com.sdgakj.entity.Permission;
import com.sdgakj.enums.EnumIsDelete;
import com.sdgakj.repository.PermissionDao;


@Component
@Transactional
public class PermissionService {
	
	@Autowired
	private PermissionDao permissionDao;
	
	private static Logger logger =LoggerFactory.getLogger(PermissionService.class);
	
	/**
	 * 根据id查询权限
	 * @param id
	 * @return
	 */
	public Permission getPermissionById(Long id) {
		// TODO Auto-generated method stub
		return permissionDao.findOne(id);
	}
	
	/**
	 * 查询未删除的所有权限
	 * @param deltag
	 * @return
	 */
	public String getAllPermission(String deltag,List<Long> checkList){
		List<Permission> permissionList= permissionDao.getAllPerimission(deltag);
		StringBuilder strBuilder =new StringBuilder();
		strBuilder.append("[");
		for(Permission p :permissionList){
			strBuilder.append("{\'id\':'"+p.getId()+"'");
			// 判断是否已经被选中
			if(checkList.contains(p.getId())){
				strBuilder.append(",\'checked\':'"+true+"'");
			}
			if(null !=p.getParent()){
				strBuilder.append(",\'pId\':'"+p.getParent().getId()+"'");
				strBuilder.append(",\'open\':'"+true+"'");
			}else{
				strBuilder.append(",\'pId\':'"+0+"'");
				strBuilder.append(",\'open\':'"+true+"'");
			}
			strBuilder.append(",\'name\':'"+p.getName()+"'");
			if(ObjectUtils.equals(p, permissionList.get(permissionList.size()-1))){
				strBuilder.append("}");
			}else{
				strBuilder.append("},");
			}
		}
		strBuilder.append("]");
		return strBuilder.toString();
	}
	 
	/**
	 * 保存Permission
	 * @param entity
	 */
	public void savePermission(Permission entity){
		permissionDao.save(entity);
	}
	
	/**
	 * 查询列表
	 * @param userType
	 * @param searchParams
	 * @param pageNumber
	 * @param pageSize
	 * @param sortType
	 * @return
	 */
	public Page<Permission> getPermissions(Map<String,Object> searchParams,int pageNumber,int pageSize,
									String sortType){
		PageRequest pageRequest =buildPageRequest(pageNumber,pageSize,sortType);
		Specification<Permission> spec =buildSpecification(searchParams);
		
		return permissionDao.findAll(spec,pageRequest);
	}
	
	/**
	 * 更新权限信息
	 * @param entity
	 * @return 
	 */
	public Permission updatePermission(Permission entity){
		return permissionDao.save(entity);
	}	
	
	/**
	 * ajax请求根据操作级别获取permission
	 * @param type 按钮级别，如主菜单，子菜单，按钮
	 * @param pid  所属主菜单id
	 * @return
	 */
	public List<Permission> getPermissionByType(String type,Long parentid){
		Map<String, SearchFilter> filters = Maps.newHashMap();
		filters.put("type", new SearchFilter("type", Operator.EQ, type)); // 当前要查看的检测项等级
		filters.put("deltag", new SearchFilter("deltag", Operator.EQ, EnumIsDelete.NOTDELETE.getCode())); //未删除
		if(-1 != parentid){
			filters.put("parent.id", new SearchFilter("parent.id", Operator.EQ, parentid)); //父节点
		}

		Specification<Permission> spec = DynamicSpecifications.bySearchFilter(filters.values(), Permission.class);
		return permissionDao.findAll(spec);
	}
	
	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.ASC, "id");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}
	
	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Permission> buildSpecification(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		//  根据用户类型设置查询条件
//		filters.put("user.type", new SearchFilter("user.type", Operator.EQ, EnumUserType.CUSTOMOR.getCode()));
		Specification<Permission> spec = DynamicSpecifications.bySearchFilter(filters.values(),Permission.class);
		return spec;
	}
}
